package com.gg.baselibrary

import android.os.Bundle
import android.support.annotation.IdRes
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import com.lsxiao.apollo.core.Apollo
import com.lsxiao.apollo.core.contract.ApolloBinder
import com.trello.rxlifecycle2.components.support.RxFragment


/**
 * Creator : GG
 * Time    : 2017/10/29
 * Mail    : gg.jin.yu@gmail.com
 * Explain :
 */
abstract class BaseFragment : RxFragment() {

    private var mRootView: View? = null

    private var mBinder: ApolloBinder? = null

    /**
     * 是否对用户可见
     */
    protected var mIsVisible: Boolean = false
    /**
     * 是否加载完成
     * 当执行完onViewCreated方法后即为true
     */
    protected var mIsPrepare: Boolean = false

    /**
     * 是否加载完成
     * 当执行完onViewCreated方法后即为true
     */
    protected var mIsImmersion: Boolean = false

    override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
        if (mRootView == null)
            mRootView = inflater.inflate(getLayoutResId(), container, false)
        return mRootView
    }

    abstract fun getLayoutResId(): Int

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        if (useBus())
            mBinder = Apollo.bind(this)
        if (isLazyLoad()) {
            mIsPrepare = true
            mIsImmersion = true
            onLazyLoad()
        } else {
            initData()
        }
        initView()
    }

    open fun useBus(): Boolean = false

    override fun onDestroy() {
        super.onDestroy()
        if (useBus() && null != mBinder) {
            mBinder!!.unbind()
        }
    }

    override fun setUserVisibleHint(isVisibleToUser: Boolean) {
        super.setUserVisibleHint(isVisibleToUser)

        if (userVisibleHint) {
            mIsVisible = true
            onVisible()
        } else {
            mIsVisible = false
            onInvisible()
        }
    }

    /**
     * 初始化数据
     */
    /**
     * 初始化数据
     */
    open fun initData() {

    }

    /**
     * view与数据绑定
     */
    open fun initView() {

    }

    /**
     * 是否懒加载
     *
     * @return the boolean
     */
    open fun isLazyLoad(): Boolean {
        return true
    }

    /**
     * 用户可见时执行的操作
     */
    open fun onVisible() {
        onLazyLoad()
    }

    private fun onLazyLoad() {
        if (mIsVisible && mIsPrepare) {
            mIsPrepare = false
            initData()
        }
    }

    /**
     * 用户不可见执行
     */
    open fun onInvisible() {

    }

    /**
     * 找到activity的控件
     *
     * @param <T> the type parameter
     * @param id  the id
     * @return the t
    </T> */
    open fun <T : View> findActivityViewById(@IdRes id: Int): T? {
        return activity?.findViewById<T>(id)
    }

}